package com.supply.service.impl;

import com.supply.mapper.UserMapper;
import com.supply.pojo.User;
import com.supply.pojo.UserExample;
import com.supply.req.UserReq;
import com.supply.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User queryByUsercode(String usercode) {
        UserExample example = new UserExample();
        example.createCriteria().andUsercodeEqualTo(usercode);
        List<User> users = userMapper.selectByExample(example);
        return users.isEmpty() ? null : users.get(0);
    }

    @Override
    public User queryById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateById(User user) {
        return userMapper.updateByPrimaryKey(user);
    }

    @Override
    public List<User> queryByCondition(UserReq userReq) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        if (!ObjectUtils.isEmpty(userReq.getUsername())){
            criteria.andUsernameLike("%" + userReq.getUsername() + "%");
        }
        if (!ObjectUtils.isEmpty(userReq.getDeptId())){
            criteria.andDeptIdEqualTo(userReq.getDeptId());
        }
        if (!ObjectUtils.isEmpty(userReq.getRoleId())){
            criteria.andRoleIdEqualTo(userReq.getRoleId());
        }
        return userMapper.selectByExample(example);
    }

    @Override
    public int saveOrUpdate(User user) {
        if (user.getId() != null){
            return userMapper.updateByPrimaryKey(user);
        }else {
            Md5Hash md5Hash = new Md5Hash(user.getPassword(),user.getUsercode(),3);
            user.setPassword(md5Hash.toString());
            return userMapper.insert(user);
        }
    }

    @Override
    public int deleteById(Long id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<User> queryAll() {
        return userMapper.selectByExample(null);
    }
}
